package org.flower.web.servlet;

import org.flower.dao.ShoppingCartDao;
import org.flower.dao.impl.ShoppingCartDaoImpl;
import org.flower.entity.ShoppingCart;
import org.flower.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns ="/user/clickAddShopping.shtml")
public class clickAddShoppingServlet extends HttpServlet {
    /**
     * 使用同步的方式 点击加入购物车
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理字符编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取登录的该用户
        User u = (User)request.getSession().getAttribute("user");
        ShoppingCartDao shdao = new ShoppingCartDaoImpl();
        //获取商品编号
        String id = request.getParameter("id");
        //获取用户编号
        int uid = u.getId();
        int comId = Integer.parseInt(id);
        //查询 该用户的该商品 有没有添加过
        boolean isAdd = shdao.getisExistByComIdAndUid(uid,comId);
        //如果该用户添加过该商品 该商品数量+1  如果没有添加过 则添加该商品信息
        if(isAdd){
            shdao.updateShoppingNum(uid,comId,1);
        }else{
            //创建购物车对象
            ShoppingCart shopping = new ShoppingCart();
            shopping.setUserId(uid);
            shopping.setComDetailsId(comId);
            shdao.addShoppingCart(shopping);
        }
        //操作成功 页面重定向
        response.sendRedirect("shoppingCart.shtml");
    }
}
